'use strict';

const Service = require('egg').Service;

class IdleFavoriteService extends Service {
  async create(data) {
    const { ctx } = this;
    return await ctx.model.IdleFavorite.create(data);
  }

  async deleteById(id) {
    const { ctx } = this;
    const favorite = await ctx.model.IdleFavorite.findByPk(id);
    if (!favorite) {
      ctx.throw(404, '收藏记录不存在');
    }
    return await favorite.destroy();
  }

  async toggle(user_id, item_id) {
    const { ctx } = this;

    // 检查物资/设备是否存在
    const item = await ctx.model.IdleItem.findByPk(item_id);
    if (!item) {
      ctx.throw(404, '物资/设备不存在');
    }

    // 查找是否已收藏
    const favorite = await ctx.model.IdleFavorite.findOne({
      where: {
        user_id,
        item_id
      }
    });

    // 如果已收藏，则取消收藏
    if (favorite) {
      await favorite.destroy();
      return { isFavorite: false };
    }

    // 如果未收藏，则添加收藏
    await this.create({
      user_id,
      item_id
    });

    return { isFavorite: true };
  }

  async getMyFavorites(user_id, query) {
    const { ctx } = this;
    const page = parseInt(query.pageNum) || 1;
    const size = parseInt(query.pageSize) || 10;

    const { count, rows } = await ctx.model.IdleFavorite.findAndCountAll({
      where: { user_id },
      offset: (page - 1) * size,
      limit: size,
      order: [['create_time', 'DESC']],
      include: [{
        model: ctx.model.IdleItem,
        include: [{
          model: ctx.model.IdleCategory,
        }]
      }]
    });

    return { count, rows };
  }

  async check(user_id, item_id) {
    const { ctx } = this;

    // 查找是否已收藏
    const favorite = await ctx.model.IdleFavorite.findOne({
      where: {
        user_id,
        item_id
      }
    });

    return { isFavorite: !!favorite };
  }
}

module.exports = IdleFavoriteService;
